package com.passioneffect.collection {

	/**
	 * @author Passion Effect
	 */
	public class LinkListCollection extends SimpleList {

		public function LinkListCollection(data :*= null) {
			if(data is Array) {
				addItems(data);
			}else if(data is LinkListCollection) {
				var list : LinkListCollection = LinkListCollection(data);
				startItem = list.getStartItem();
				endItem = list.getEndItem();
				total = list.getLength();
			}
		}

		public function addItems(data : Array) : void {
			if(data.length == 0)return;
			var startIndex : int = 0;
			
			if(total == 0) {
				endItem = startItem = new ListItem(data[0]);
				startIndex = 1;
				total = 1;
			}
			var length : int = data.length;
			var item : ListItem;
			for(var i : int = startIndex;i < length;i++) {
				item = new ListItem(data[i]);
				endItem = endItem.insertBehind(item);
				++total;
			}
		}

		public function addItemAt(data : *,index : int) : void {
			if(data == null)return;
			var newItem : ListItem = new ListItem(data);
			var item : ListItem;

			if(total == 0) {
				startItem = endItem = newItem;
			}else if(index != total) {
				item = getItemAt(index);
				item.insertFront(newItem);
			}else {
				endItem = endItem.insertBehind(newItem);
			}
			
			++total;
		}

		
		
		public function getItemDataAt(index : int) : * {
			return getItemAt(index).getData();
		}

		

		public function getItem(data : *) : ListItem {
			var item : ListItem;
			var itr : LinkListIterator = iterator();
			while(itr.hasNext()) {
				item = itr.next();
				if(item.getData() == data) {
					return item;
				}
			}
			return null;
		}

		public function removeItemWithData(data : *) : Boolean {
			return removeItem(getItem(data));
		}

		public function removeItemAt(index : int) : Boolean {
			return removeItem(getItemAt(index));
		}
		
		public function containsData(data:*):Boolean{
			var itr:LinkListIterator=iterator();
			while(itr.hasNext()){
				if(itr.next().getData()==data){
					return true;
				}
			}
			return false;
		}
		
		public function removeItem(item : ListItem) : Boolean {
			
			if(item == null)return false;
			
			if(startItem == endItem == item) {
				startItem = endItem = null;
				item.remove();	
			}else {
				if(startItem == item) {
					startItem = item.next;
				}else if(endItem == item) {
					endItem = item.previous;
				}
			}
			
			item.remove();
			--total;
			return true;
		}

		public function clone() : LinkListCollection {
			return new LinkListCollection(this);
		}
	}
}
